import { IHttpResponse, RuntimeError } from '@ibiz-template/core';
import {
  ICalendarItemData,
  MDControlService,
  CalendarItemData,
} from '@ibiz-template/runtime';
import { ISysCalendar } from '@ibiz/model-core';

/**
 * 日历部件服务
 *
 * @author zk
 * @date 2023-08-08 10:08:54
 * @export
 * @class CalendarService
 * @extends {MDControlService<ISysCalendar>}
 */
export class CalendarService extends MDControlService<ISysCalendar> {
  /**
   * 执行查询多条数据的方法
   *
   * @author zk
   * @date 2023-08-08 10:08:47
   * @param {IParams} context
   * @param {IParams} [params={}]
   * @return {*}  Promise<ICalendarItemData[]>
   * @memberof CalendarService
   */
  async search(
    context: IParams,
    params: IParams = {},
  ): Promise<ICalendarItemData[]> {
    const { sysCalendarItems } = this.model;
    if (!sysCalendarItems) {
      return [];
    }
    const promises = sysCalendarItems.map(
      async (item): Promise<IHttpResponse> => {
        const fetchAction = item.appDEDataSetId || 'fetchdefault';
        return this.exec2(
          fetchAction,
          context,
          params,
          undefined,
          item.appDataEntityId!,
        );
      },
    );
    const resArray = await Promise.all(promises);
    // 二维数组
    const twoDimensionalArray = resArray.map(
      (res: IHttpResponse, index: number) => {
        return this.setCalendarConfigData(res.data as IData[], index);
      },
    );
    return twoDimensionalArray.flat();
  }

  /**
   * 设置日历项配置
   *
   * @author zk
   * @date 2023-08-08 06:08:14
   * @param {IData[]} items
   * @param {number} index
   * @return {*}  {ICalendarItemData[]}
   * @memberof CalendarService
   */
  private setCalendarConfigData(
    items: IData[],
    index: number,
  ): ICalendarItemData[] {
    const { sysCalendarItems } = this.model;
    if (!sysCalendarItems) {
      throw new RuntimeError('未找到日历项模型');
    }
    const calendarItem = sysCalendarItems[index];
    if (!calendarItem) {
      throw new RuntimeError('未找到日历项模型');
    }
    return items.map(item => {
      return new CalendarItemData(calendarItem, item);
    });
  }

  /**
   * 执行方法实体方法（通过实体id和方法名）
   *
   * @author zk
   * @date 2023-08-08 06:08:49
   * @param {string} methodName
   * @param {IParams} context
   * @param {IData} [data={}]
   * @param {IParams} [params={}]
   * @param {string} [appDataEntityId=this.model.appDataEntityId!]
   * @return {*}  {Promise<IHttpResponse>}
   * @memberof CalendarService
   */
  private async exec2(
    methodName: string,
    context: IParams,
    data: IData = {},
    params: IParams = {},
    appDataEntityId: string = this.model.appDataEntityId!,
  ): Promise<IHttpResponse> {
    const res = await this.app.deService.exec(
      appDataEntityId!,
      methodName,
      context,
      data,
      params,
    );
    return res;
  }
}
